package com.kld.shop.controller.product;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ProductNode;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.page.PageInfoResult;
import com.kld.product.api.IProMctService;
import com.kld.product.api.IProPrctrueService;
import com.kld.product.api.IProProductService;
import com.kld.product.api.IProServerService;
import com.kld.product.dto.ProductDto;
import com.kld.product.po.ProMct;
import com.kld.product.po.ProPrctrue;
import com.kld.product.po.ProProduct;
import com.kld.product.po.ProServer;
import com.kld.shop.allocation.Constant;
import com.kld.shop.controller.base.BaseController;
import com.kld.sys.api.ISysDictService;
import com.kld.sys.po.SysDict;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by anpushang on 2016/4/3.
 */
@Controller
@RequestMapping("/admin/pro")
public class ProductController extends BaseController {

    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IProProductService proProductService;
    @Autowired
    private IProMctService proMctService;
    @Autowired
    private IProPrctrueService proPrctrueService;
    @Autowired
    private IProServerService proServerService;

    @RequestMapping(value = "/toList")
    public String toList(){
        return "/admin/newProduct/product_list";
    }


    /***
     * 分页查询商品
     * @param proProduct
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/list")
    public ResultMsg list(ProProduct proProduct){
        PageInfo pageInfo = null;
        try{
            proProduct.setIsDel(Constant.ENABLE);
            pageInfo = proProductService.findProProductListPage(getPageNum(), getPageSize(), proProduct);
        }catch (Exception e){
            logger.error("分页查询商品"+e.getMessage(),e);
            e.printStackTrace();
        }
        return PageInfoResult.PageInfoMsg(pageInfo);
    }




    /***
     * 获得下拉选信息
     * @param par
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getProductConstent")
    public String getProductConstent(String par){
        String jsonStr = "";
        try{
            Map<String,Object> productTypeMap = new ConcurrentHashMap<String,Object>();
            productTypeMap.put("parentcode",par);
            List<SysDict> productTypeList = sysDictService.getSysDictList(productTypeMap);
            List<ProductNode> productNodeList = new ArrayList<ProductNode>();
            for (SysDict sysDict : productTypeList) {
                ProductNode productNode = new ProductNode();
                productNode.setId(String.valueOf(sysDict.getDictcode()));
                productNode.setPid(String.valueOf(sysDict.getParentcode()));
                productNode.setText(sysDict.getValue());
                productNodeList.add(productNode);
            }
            JSONArray jsonArray = JSONArray.fromObject(productNodeList);
            jsonStr = String.format("%s", JSON.toJSONString(jsonArray));
        }catch (Exception e){
            logger.error("获得下拉选信息"+e.getMessage(),e);
            e.printStackTrace();
        }
        return jsonStr;
    }

    /***
     * 到商品修改的界面
     * @param id
     * @return
     */
    @RequestMapping(value = "toUpdatePage")
    public ModelAndView toUpdatePage(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        try{

            //得到商品基本信息
            ProProduct proProduct = proProductService.selectByPrimaryKey(id);
            //商品图片
            List<ProPrctrue> prctrueList = proPrctrueService.selectByProId(id);
            List<String> imageList = new ArrayList<String>();
            imageList.add(proProduct.getPicUrl());
            for (ProPrctrue proPrctrue : prctrueList) {
                imageList.add(proPrctrue.getProUrl());
            }
            JSONArray imageArray = JSONArray.fromObject(imageList);
            //查询已选择的服务
            List<ProServer> proServerList = proServerService.selectByProId(id);

            modelAndView = getProSerList(modelAndView, proServerList);
            //获取售后服务
            Map<String,Object> productSerMap = new ConcurrentHashMap<String,Object>();
            productSerMap.put("parentcode", Constant.PRODUCT_SER);
            List<SysDict> productSerList = sysDictService.getSysDictList(productSerMap);
            //获取配送方式
            Map<String,Object> productPsMap = new ConcurrentHashMap<String,Object>();
            productPsMap.put("parentcode", Constant.PRODUCT_PS);
            List<SysDict> productPsList = sysDictService.getSysDictList(productPsMap);

            List<ProMct> proMctList = proMctService.findProMctList(new ProMct());

            modelAndView.addObject("proServerList",proServerList);
            modelAndView.addObject("imageArray",imageArray);
            modelAndView.addObject("proProduct",proProduct);
            modelAndView.addObject("productSerList",productSerList);
            modelAndView.addObject("productPsList",productPsList);
            modelAndView.addObject("proMctList",proMctList);
            modelAndView.setViewName("/admin/newProduct/product_edit");
        }catch (Exception e){
            logger.error("到商品修改的界面"+e.getMessage(),e);
            e.printStackTrace();
        }
        return modelAndView;
    }


    public ModelAndView getProSerList(ModelAndView modelAndView,List<ProServer> proServerList){
        ProServer proServer2137 = new ProServer();
        ProServer proServer2138 = new ProServer();
        ProServer proServer2149 = new ProServer();
        ProServer proServer2140 = new ProServer();
        ProServer proServer2141 = new ProServer();
        for (ProServer proServer : proServerList) {
            Integer svcId = proServer.getSvcId();
            if (svcId == 2137){ //换货
                proServer2137.setSvcId(svcId);
                proServer2137.sethXInDate(proServer.gethXInDate());
                modelAndView.addObject("proServer2137",proServer2137);
            }else if (svcId == 2138){//退货
                proServer2138.setSvcId(svcId);
                proServer2138.settHInDate(proServer.gettHInDate());
                modelAndView.addObject("proServer2138",proServer2138);
            }else if(svcId == 2149){//维修
                proServer2149.setSvcId(svcId);
                proServer2149.setMainTain(proServer.getMainTain());
                modelAndView.addObject("proServer2149",proServer2149);
            }else if(svcId == 2140){//快递运输
                proServer2140.setSvcId(svcId);
                proServer2140.setProcessMode(proServer.getProcessMode());
                modelAndView.addObject("proServer2140",proServer2140);
            }else if(svcId == 2141){//上门自提
                proServer2141.setSvcId(svcId);
                proServer2141.setProcessMode(proServer.getProcessMode());
                proServer2141.setProcessTime(proServer.getProcessTime());
                modelAndView.addObject("proServer2141",proServer2141);
            }
        }

        if (proServer2141.getProcessTime() == null){
            modelAndView.addObject("processTime","");
        }else{
            modelAndView.addObject("processTime",proServer2141.getProcessTime());
        }

        if (proServer2149.getMainTain() == null){
            modelAndView.addObject("mainTain",2146);
        }else{
            modelAndView.addObject("mainTain",proServer2149.getMainTain());
        }


        return modelAndView;
    }

    /**
     * 到添加商品界面
     * @return
     */
    @RequestMapping(value = "/toAddProduct")
    public ModelAndView toAddProduct(){
        ModelAndView modelAndView = new ModelAndView();
        try{

            //获取售后服务
            Map<String,Object> productSerMap = new ConcurrentHashMap<String,Object>();
            productSerMap.put("parentcode", Constant.PRODUCT_SER);
            List<SysDict> productSerList = sysDictService.getSysDictList(productSerMap);
            //获取配送方式
            Map<String,Object> productPsMap = new ConcurrentHashMap<String,Object>();
            productPsMap.put("parentcode", Constant.PRODUCT_PS);
            List<SysDict> productPsList = sysDictService.getSysDictList(productPsMap);

            List<ProMct> proMctList = proMctService.findProMctList(new ProMct());

            modelAndView.addObject("productSerList",productSerList);
            modelAndView.addObject("productPsList",productPsList);
            modelAndView.addObject("proMctList",proMctList);
            modelAndView.setViewName("/admin/newProduct/product_add");
        }catch (Exception e){
            logger.error("到添加商品界面"+e.getMessage(),e);
            e.printStackTrace();
        }
        return modelAndView;
    }

    /***
     * 新增 商品
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/savePro")
    public ResultMsg savePro(ProductDto productDto,String[] imgUrl){
        ResultMsg resultMsg = new ResultMsg();
        try{
            productDto.getProProduct().setOuCode(getUserOuCode());
            int resultCount = proProductService.insertProduct(productDto,imgUrl);
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.INSERT_SUCCESS) : errorMsg(resultMsg,Constant.INSERT_ERROR);
        }catch (Exception e){
            logger.error("新增商品"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }

    /***
     * 编辑商品
     * @param productDto
     * @param imgUrl
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatePro")
    public ResultMsg updatePro(ProductDto productDto,String[] imgUrl){
        ResultMsg resultMsg = new ResultMsg();
        try{
            int resultCount = proProductService.updateProById(productDto, imgUrl);
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.INSERT_SUCCESS) : errorMsg(resultMsg,Constant.INSERT_ERROR);
        }catch (Exception e){
            logger.error("编辑商品"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }

    /***
     * 到商品设置界面
     * @param id
     * @return
     */
    @RequestMapping(value = "/toProdcutSettingPage")
    public ModelAndView toProdcutSettingPage(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        try{
            //获取支付方式
            Map<String,Object> productPsMap = new ConcurrentHashMap<String,Object>();
            productPsMap.put("parentcode",2150);
            List<SysDict> proZfList = sysDictService.getSysDictList(productPsMap);

            modelAndView.addObject("proZfList",proZfList);
            modelAndView.setViewName("/admin/newProduct/product_setting");
        }catch (Exception e){
            logger.error("到商品设置界面"+e.getMessage(),e);
            e.printStackTrace();
        }
        return modelAndView;
    }

}
